<template>
  <div class="user-management-container">
    <el-card>
      <div slot="header" class="clearfix">
        <span style="float: right; padding: 1px">销售金额合计：￥{{new Intl.NumberFormat('en-US', {
          minimumFractionDigits: 2,
          maximumFractionDigits: 2
        }).format((totalPrice).toFixed(2))}}</span>
      </div>
      <el-form align="right" label-width="50">
        <el-form-item>
          <el-table
            v-loading="listLoading"
            border
            :data="list"
            row-key="id"
            default-expand-all
          >
            <el-table-column prop="no" label="序号" align="center" width="180px">
              <template #default="scope">
                <el-link :underline="false" type="primary" v-if="scope.row.index" @click="getChildren(scope.row)">{{ scope.row.index }}</el-link>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="SKU"
              show-overflow-tooltip
              width="400px"
            >
              <template #default="{row}">
                <span v-if="row.id !== 1">{{ row.sku.label }}</span>
                <el-select v-else v-model="list[0].sku_id" placeholder="选取SKU" clearable filterable style="width: 100%"
                           @change="getChildren(row)">
                  <el-option v-for="(item,key) in sku_list" :value="item.id" :key="key"
                             :label="item.label"></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="BOM占比"
              prop="sale_date"
              show-overflow-tooltip
            >
              <template #default="{row}">
                <span v-if="row.id !== 1">{{ (row.percentage).toFixed(2)}}%</span>
                <span v-else >100%</span>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="销售单价（￥）"
              show-overflow-tooltip
              width="250px"
            >
              <template #default="{row}">
                <el-input-number style="width:200px" v-model="row.unit_price" :step="0.01" placeholder="请填写" @input="updateTotalPrice" @focus="handleFocusUnitPrice" @blur="handleBlurUnitPrice"/>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="销售金额（￥）"
              prop="price"
              show-overflow-tooltip
            >
              <template #default="{row}">
                <span v-if="row.id !== 1">{{ (row.unit_price * row.percentage/100).toFixed(2) }}</span>
                <span v-else-if="row.unit_price" >{{ (row.unit_price ).toFixed(2) }}</span>
              </template>
            </el-table-column>
            <template #empty>
              <el-image
                class="vab-data-empty"
                :src="require('@/assets/empty_images/data_empty.png')"
              />
            </template>
          </el-table>
        </el-form-item>
        <el-row :gutter="20" class="text-left">
          <el-col :span="4">
            <el-form-item label="物流成本（￥）:">
              <el-input-number v-model="logistics_costs" @input="updateTotalPrice" placeholder="请输入" @focus="handleFocus('logistics_costs')" @blur="handleBlur('logistics_costs')"/>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="加工成本（￥）:">
              <el-input-number v-model="processing_costs" @input="updateTotalPrice" placeholder="请输入" @focus="handleFocus('processing_costs')" @blur="handleBlur('processing_costs')"/>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="其他成本（￥）:">
              <el-input-number v-model="other_costs" @input="updateTotalPrice" placeholder="请输入" @focus="handleFocus('other_costs')" @blur="handleBlur('other_costs')"/>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="毛利率要求(%):">
              <el-input-number v-model="gross_rate" @input="updateTotalPrice" placeholder="请输入" @focus="handleFocus('gross_rate')" @blur="handleBlur('gross_rate')"/>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="毛利:">
              ￥{{new Intl.NumberFormat('en-US', {
              minimumFractionDigits: 2,
              maximumFractionDigits: 2
            }).format(gross_profit)}}
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="含税回收价:">
              ￥{{new Intl.NumberFormat('en-US', {
              minimumFractionDigits: 2,
              maximumFractionDigits: 2
            }).format(tax_inclusive_recycling_price)}}
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

    </el-card>
  </div>
</template>

<script>
import {all as getSkuList} from '@/api/sku/classify'
import {getChildrenBySkuTool} from '@/api/bom/bom'

export default {
  watch: {
    '$route'(to, from) {
      // 路由变化时重新加载数据
      if (to.path === '/Quotation/tool') {
      // 路由变化为当前页时重新加载数据
      this.getFilter();
    }
    }
  },
  name: 'QuotationTool',
  components: {},
  filters: {},
  data() {
    return {
      gross_profit:0,
      totalPrice : 0,
      tax_inclusive_recycling_price: 0,
      gross_rate: 0,
      other_costs: 0,
      processing_costs: 0,
      logistics_costs: 0,
      sku_list: [],
      listLoading: false,
      layout: 'total, sizes, prev, pager, next, jumper',
      fileRootPath: '',
      list: [
        {
          id: 1,
          sku_id: '',
          children: [],
          unit_price :0,
          bom_id: [],
          bom_weight:0,
          bom_weight_total:0,
          percentage:100,
          link_weight:0
        }
      ],
      sum_weight: 0,

    }
  },
  created() {
    this.fileRootPath = process.env.VUE_APP_FILE_ROOT_PATH
    this.getFilter()

  },
  methods: {
    handleFocus(value){
      if (this[value]===0){
        this.$set(this,value,undefined)
      }

    },
    handleBlur(value){
      if (this[value]===undefined){
        this.$set(this,value,0)
      }
    },
    handleFocusUnitPrice(){
      if (this.list[0].unit_price===0){
        this.$set(this.list[0],'unit_price',undefined)
      }

    },
    handleBlurUnitPrice(){
      if (this.list[0].unit_price===undefined){
        this.$set(this.list[0],'unit_price',0)
      }
    },
    async getFilter() {
      getSkuList({pageNo: 'all'}).then(response => {
        this.sku_list = response.data.list
      });
    },
    getChildren(row) {
      this.listLoading = true
      getChildrenBySkuTool({pageNo: 'all', 'parent_sku_id': row.sku_id,'bom_id':row.bom_id.join(',')}).then(response => {
        if(!row.bom_id.length) {
          row.link_weight = this.sum_weight = response.data.sum_weight
        }
        for(var i =0;i<response.data.list.length;i++){
          if (row.index) {
            response.data.list[i].index = String(row.index) + '-' + String(response.data.list[i].index)
          }
          // if (response.data.list[i].bom_id.length){
          //   response.data.list[i].percentage = response.data.list[i].bom_weight/row.link_weight*row.percentage
          // }
          response.data.list[i].percentage = response.data.list[i].bom_weight/row.link_weight*row.percentage
        }
        this.$set(row,'children',response.data.list)
        this.listLoading = false

      })
    },
    reset() {

    },
    getTotalPrice(total,bom){
      for(var i =0;i<bom.length;i++){
        total += parseFloat(bom[i].unit_price) * bom[i]['percentage']/100;
        if (bom[i].children.length>0){
          total += this.getTotalPrice(total,bom[i].children)
        }
      }
      return total
    },
    updateTotalPrice(){
      if (this.list[0].children.length) {
        this.totalPrice  = this.getTotalPrice(0,this.list[0].children)
      }else if(this.list[0].unit_price){
        this.totalPrice = this.list[0].unit_price
      }else{
        this.totalPrice=0
      }
      this.tax_inclusive_recycling_price = (this.totalPrice*(100-this.gross_rate)/100-this.logistics_costs-this.processing_costs-this.other_costs).toFixed(2)
      this.gross_profit = (this.totalPrice-this.tax_inclusive_recycling_price-this.logistics_costs-this.processing_costs-this.other_costs).toFixed(2)
    },

  },
}
</script>
<style lang="scss" scoped>
.text-left {
  text-align: left;
}
.list-container {
  ul {
    padding: 0;
    margin: 0;
    list-style: none;
    outline: none;

    .list-item {
      padding: $base-padding;
      //border-bottom: 1px solid $base-border-color;

      &-meta {
        display: flex;
        flex: 1 1;
        align-items: flex-start;

        &-avatar {
          margin-right: 16px;

          ::v-deep {
            .el-image {
              width: 61px;
              height: 61px;
            }
          }
        }

        &-content {
          flex: 1 0;
          width: 0;
          color: rgba(0, 0, 0, 0.85);
        }

        &-title {
          margin-top: 11px;
          margin-bottom: 4px;
          font-size: 14px;
          color: rgba(0, 0, 0, 0.85);
        }

        &-description {
          font-size: 14px;
          color: rgba(0, 0, 0, 0.45);
        }

        &-item {
          display: inline-block;
          height: 61px;
          margin-left: 40px;
          font-size: 14px;
          color: rgba(0, 0, 0, 0.45);
          vertical-align: middle;

          > span {
            line-height: 30px;
          }

          > p {
            margin-top: 4px;
            margin-bottom: 0;
          }
        }

        ::v-deep {
          .el-progress {
            margin-top: 21px;
          }
        }
      }
    }
  }
}
</style>
